import React, { useEffect, useState, useCallback, useRef } from 'react';
import { Avatar, Button, Modal, Toast, Popup } from 'antd-mobile';
import { useDispatch } from 'umi';
import NavBarItem from '@/component/NavBarItem';
import {
  fetchUserInfo,
  fetchUserNickname,
  fetchUserAva,
} from '@/services/user';
import Avapop from './component/Avapop';
import styles from './index.less';

const User: React.FC = () => {
  const dispatch = useDispatch();
  const [userInfo, setUserInfo] = useState<any>({});
  const [visible, setVisible] = useState<boolean>(false);
  const nicknameRef = useRef<string>('');
  useEffect(() => {
    fetchUserInfo().then((res) => {
      setUserInfo(res);
    });
  }, []);

  const handleLayout = useCallback(() => {
    dispatch({
      type: 'login/getLayout',
    });
  }, []);

  const handleNickname = useCallback(() => {
    Modal.confirm({
      content: (
        <input
          placeholder="请输入昵称"
          className={styles.nameInput}
          onChange={(e) => {
            nicknameRef.current = e.target.value;
          }}
        />
      ),
      closeOnMaskClick: true,
      onConfirm: async () => {
        const res = await fetchUserNickname(nicknameRef.current);
        if (!res) {
          fetchUserInfo().then((res) => {
            setUserInfo(res);
          });
          Toast.show({
            icon: 'success',
            content: '修改成功',
          });
        } else {
          Toast.show({
            icon: 'fail',
            content: '修改失败',
          });
        }
      },
    });
  }, []);

  const handleAvater = useCallback(() => {
    setVisible(true);
  }, []);

  const handleClosePop = useCallback(() => {
    setVisible(false);
  }, []);

  return (
    <>
      <NavBarItem title="个人中心" />
      <div className={styles.userInfo}>
        <Avatar src={userInfo.avatar_url} className={styles.ava} />
        <div>
          <p className={styles.username}>{userInfo.name}</p>
          <span className={styles.useremial}>{userInfo.email} </span>
        </div>
      </div>
      <div className={styles.change}>
        <p onClick={handleNickname}>修改昵称</p>
        <p onClick={handleAvater}>修改头像</p>
      </div>
      <Button block size="large" onClick={handleLayout}>
        退出登录
      </Button>
      <Avapop visible={visible} onClose={handleClosePop} />
    </>
  );
};
export default User;
